package com.fare.taluo.application.impl.queue;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.dayatang.domain.Entity;
import com.fare.taluo.application.queue.IScheduleQueueApplication;
import com.fare.taluo.core.domain.queue.QueueBaseEntity;
import com.fare.taluo.util.ClassUtils;
import com.fare.taluo.vo.queue.QueueBaseVO;
/**
 * 队列应用模板
 * @author creator: xiangsf
 * @author modifior: xiangsf
 * @since 2012-12-19 下午1:51:22
 * @version v1.0
 */
@Transactional
public abstract class ScheduleQueueApplicationImpl<X extends QueueBaseVO>
		implements IScheduleQueueApplication<X>  {
	
	protected Logger logger = Logger.getLogger(getClass());
	
	@Override
	public List<X> getPlanTask(int maxSize) throws Exception{
		List<QueueBaseEntity<?>> list = (List<QueueBaseEntity<?>>)this.newInstance().getPlanTask(maxSize);
		return this.listConverts(list);
	}
	@Override
	public boolean load(Long id) throws Exception {
		return this.newInstance().loadTask(id);
	}

	@Override
	public boolean execute(Long id) throws Exception{
		this.newInstance().executeTask(id);
		return true;
	}

	@Override
	public boolean archive(QueueBaseVO vo) throws Exception{
		this.newInstance().archiveTask(vo);
		return true;
	}

	@Override
	public boolean createNext(Long id) throws Exception{
		this.newInstance().createNextTask(id);
		return false;
	}

	@Override
	public boolean reset() throws Exception{
		return false;
	}

	
	protected List<X> listConverts(List<QueueBaseEntity<?>> results) throws Exception{
		List<X> list = new ArrayList<X>();
		QueueBaseVO vo = null;
		if(results != null && !results.isEmpty()){
			for(QueueBaseEntity<?> entity : results){
				vo = (QueueBaseVO)ClassUtils.getGenericType(this.getClass()).newInstance();
				vo.setId(entity.getId());
				vo.setCreateTime(entity.getCreateTime());
				vo.setEndTime(entity.getEndTime());
				vo.setName(entity.getName());
				vo.setPlanStartTime(entity.getPlanStartTime());
				vo.setRecLog(entity.getRecLog());
				vo.setSpentTimes(entity.getSpentTimes());
				vo.setStartTime(entity.getStartTime());
				vo.setStatus(entity.getStatus());
				
				list.add((X)vo);
			}
		}
		return list;
	}

	protected abstract QueueBaseEntity<? extends Entity> newInstance() throws Exception;
}
